package com.ztx.web.controller.sys;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ztx.model.User;
import com.ztx.pagemodel.easyui.DataGrid;
import com.ztx.pagemodel.easyui.Json;
import com.ztx.pagemodel.easyui.PageHelper;
import com.ztx.pagemodel.easyui.Tree;
import com.ztx.service.base.IBaseService;
import com.ztx.service.user.IUserService;
import com.ztx.utils.Utils;

/**
 * 
 * 用户管理
 * 
 */
@Controller
@RequestMapping("/userController")
public class UserController {

	private static final Logger log = LoggerFactory
			.getLogger(UserController.class);

	@Resource
	private IUserService userService = null;

	@Resource
	private IBaseService baseService = null;

	/**
	 * 跳转到用户列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/manager", method = RequestMethod.GET)
	public String userList() {
		return "admin/user";
	}

	@RequestMapping(value = "/datagrid")
	@ResponseBody
	public DataGrid<User> dataGrid(User user, PageHelper ph) {
		return userService.userDataGrid(user, ph);
	}

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add() {
		return "admin/adduser";
	}

	/**
	 * 保存用户数据
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Json add(User user) {
		Json json = new Json();
		user.setId(Long.toString(Utils.createId()));
		try {
			userService.addUser(user);
		} catch (Exception e) {
			json.setSuccess(false);
			json.setMsg(e.getMessage());
		}
		return json;
	}

	/**
	 * 查询用户角色
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "getUserRoles", method = RequestMethod.POST)
	@ResponseBody
	public List<Tree> getUserRoles(String userId) {
		List<Tree> list = null;
		try {
			list = userService.getUserRoles(userId);
		} catch (Exception e) {
			log.error("查询用户角色错误", e);
		}
		return list;
	}

	/**
	 * 保存用户角色关联信息
	 * 
	 * @param userId
	 * @param roleIds
	 * @return
	 */
	@RequestMapping(value = "addUserRole", method = RequestMethod.POST)
	@ResponseBody
	public Json addUserRole(String userId, String[] roleIds) {
		Json json = new Json();
		try {
			userService.saveUserRole(userId, roleIds);
		} catch (Exception e) {
			json.setSuccess(false);
			json.setMsg(e.getMessage());
			log.error("保存用户角色关联信息失败", e);
		}
		return json;
	}
}
